package com.qingyun.customview.nestscroll1

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.widget.LinearLayout
import kotlin.math.abs

class MyNestScrollView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
) : LinearLayout(context, attrs, defStyleAttr) {
    private val TAG = "MyNestScrollView"
    private var mTouchSlop = 0
    private var startY = 0f
    private var mTopViewHeight = 0

    init {
        mTouchSlop = ViewConfiguration.get(context).scaledPagingTouchSlop
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mTopViewHeight = getChildAt(0).measuredHeight
    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        /**
         * 什么时候拦截事件？
         * 当头部还没有消失的时候，拦截时间交由父容器消费
         * */
        var intercept = false
        when (ev?.action) {
            MotionEvent.ACTION_DOWN -> {
                startY = ev.rawY
            }

            MotionEvent.ACTION_MOVE -> {
                val endY = ev.rawY
                if (abs(startY - endY) > mTouchSlop) {
                    if (isViewHidden((startY - endY).toInt()) || isViewShow((startY - endY).toInt())) {
                        Log.e(TAG, "此时就需要拦截，外部进行消费事件")
                        intercept = true
                    }
                }
                startY = endY
            }
        }
        return intercept
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_DOWN -> {
                Log.d(TAG, "MyNestScrollView ACTION_DOWN")
                startY = event.y
            }

            MotionEvent.ACTION_MOVE -> {
                Log.d(TAG, "MyNestScrollView ACTION_MOVE")
                val endY = event.y
                if (abs(endY - startY) > mTouchSlop) {
                    //滑动了
                    scrollBy(0, (startY - endY).toInt())
                }
                startY = endY
            }
        }
        return super.onTouchEvent(event)
    }

    /**
     * 头部逐渐消失
     */
    private fun isViewHidden(dy: Int): Boolean {
        return dy > 0 && scrollY < mTopViewHeight
    }

    private fun isViewShow(dy: Int): Boolean {
        return dy < 0 && scrollY > 0 && !canScrollVertically(-1)
    }

    override fun scrollTo(x: Int, y: Int) {
        Log.d(TAG, "scrollTo: $y")
        var finalY = 0
        if (y < 0) {

        } else {
            finalY = y
        }
        if (y > mTopViewHeight) {
            finalY = mTopViewHeight
        }
        super.scrollTo(x, finalY)
    }
}